﻿using lyAdmin.Entity;
using lyAdmin.Repository.IRepository;
using System;
using System.Collections.Generic;
using System.Text;

namespace lyAdmin.Repository
{
    public class DBFactory
    {
        private lyAdminContext context=null;
        /// <summary>
        /// 获取仓库
        /// </summary>
        /// <param name="dbEnum">仓库名称</param>
        /// <param name="tran">使用事务</param>
        /// <returns>仓库</returns>
        public lyAdmin.Repository.IRepository.IRepository Get(DBEnum dbEnum,bool tran = false)
        {
            Type type = Type.GetType("lyAdmin.Repository." + dbEnum.ToString());
            lyAdmin.Repository.IRepository.IRepository iRepository = null;
            if(!tran)
                iRepository = (lyAdmin.Repository.IRepository.IRepository)System.Activator.CreateInstance(type);
            else if (tran && context == null)
            {
                iRepository = (lyAdmin.Repository.IRepository.IRepository)System.Activator.CreateInstance(type); 
                context = iRepository.getContext();
                context.Database.BeginTransaction();
            }
            else if (tran && context!=null)
                iRepository = (lyAdmin.Repository.IRepository.IRepository)System.Activator.CreateInstance(type, context); 
            return iRepository;
        }
        /// <summary>
        /// 提交事务
        /// </summary>
        /// <returns>是否执行成功</returns>
        public bool CommitTran()
        {
            if (context == null)
                return false;
            try
            {
                context.Database.CommitTransaction();
                return true;
            }
            catch (Exception)
            {
                context.Database.RollbackTransaction();
                return false;
            }
        }
        /// <summary>
        /// 事务回滚
        /// </summary>
        public void RollbackTran()
        {
            if(context!=null)
                context.Database.RollbackTransaction();
        }
    }
}
